#include "stdafx.h"
#include "doc.h"

XmlDocument::XmlDocument()
{
	HRESULT hres;
	hres = CoCreateInstance(CLSID_DOMDocument, 0, CLSCTX_INPROC_SERVER, 
		IID_IXMLDOMDocument, (void**)&pDoc);
	if(hres != S_OK)
		throw Exception("Couldn't create an MSXML document");
}

XmlDocument::XmlDocument(const XmlDocument &src)
{
	pDoc = (IXMLDOMDocument*)src.pDoc;
	pDoc->AddRef();
}

XmlDocument::~XmlDocument()
{
	pDoc->Release();
}

XmlElement XmlDocument::CreateRootElement(const std::string &name)
{
	IXMLDOMElement *pElement;

	BSTR nameStr = _com_util::ConvertStringToBSTR(name.c_str());
	HRESULT hres = pDoc->createElement(nameStr,&pElement);
	SysFreeString(nameStr);
	if(hres != S_OK)		
		throw Exception("Couldn't create an MSXML element");

	hres = pDoc->putref_documentElement(pElement);
	assert(hres == S_OK);
		
	return XmlElement(pElement,true);
}

void XmlDocument::Write(const std::string &fileName) const
{
	BSTR fileNameBSTR = _com_util::ConvertStringToBSTR(fileName.c_str());
	HRESULT hres = pDoc->save(_variant_t(fileNameBSTR));
	SysFreeString(fileNameBSTR);
	if(hres != S_OK)
		throw Exception("Couldn't save the xml document to " + fileName);
}